package org.spring.blog.service.impl;

import org.spring.blog.pojo.User;
import org.spring.blog.service.IUserService;
import org.spring.blog.utils.CookieUtil;
import org.spring.blog.utils.TextUtil;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Service("permission")
public class PermissionService {

    private final IUserService userService;

    public PermissionService(IUserService userService) {
        this.userService = userService;
    }

    /**
     * 判断是不是管理员
     */
    public boolean admin() {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

        assert servletRequestAttributes != null;
        HttpServletRequest request = servletRequestAttributes.getRequest();

        String token_key = CookieUtil.getCookieValue(request, IUserService.constant.cookie_token_key);

        if (TextUtil.isEmpty(token_key)) {
            return false;
        }

        User user = userService.checkUserIsLogin();

        if (user == null) {
            return false;
        }

        return user.getRoles().equals(IUserService.constant.DB_ROLE_ADMIN);
    }
}
